// ** React Imports
import { Fragment, useState, forwardRef, useEffect } from 'react'
// ** Table Data & Columns
import { data, columns } from './data'

// ** Third Party Components
import ReactPaginate from 'react-paginate'
import DataTable from 'react-data-table-component'
import { ChevronDown, Plus, AlertCircle } from 'react-feather'
import ToastCommon from '../components/toasts/ToastCommon'
import toast from 'react-hot-toast'
import axios from '../../configs/request'
import ConfirmModal from '../components/confirmModal'

// ** Reactstrap Imports
import {
  Row,
  Col,
  Card,
  Input,
  Button,
  CardTitle,
  CardHeader,
  Modal,
  ModalHeader,
  ModalBody,
  ModalFooter,
  Alert,
  Label,
} from 'reactstrap'

// ** Bootstrap Checkbox Component
const BootstrapCheckbox = forwardRef((props, ref) => (
  <div className="form-check">
    <Input type="checkbox" ref={ref} {...props} />
  </div>
))

const DataTableWithButtons = () => {
  // ** States
  const [currentPage, setCurrentPage] = useState(0)
  const [searchValue, setSearchValue] = useState('')
  const [filteredData, setFilteredData] = useState([])
  const [modalShow, setModalShow] = useState(false)
  const [listData, setListData] = useState(data)
  const [alertShow, setAlertShow] = useState(false)
  const [isNew, setIsNew] = useState(false)
  const [id, setId] = useState('')
  const [confirmModalShow, setConfirmModalShow] = useState(false)
  const [name, setName] = useState('')
  const [number, setNumber] = useState('')

  useEffect(() => {
    getList()
  }, [])

  useEffect(() => {
    searchData()
  }, [searchValue])

  // 获取列表
  const getList = () => {
    axios
      .post('/department/list')
      .then((res) => {
        if (res.status === 200) {
          setListData(res.data)
        }
      })
      .catch(() => {
        console.error('error')
      })
  }

  // 搜索
  const searchData = () => {
    const filterData = listData.filter(
      (item) =>
        item.name.toLowerCase().includes(searchValue.toLowerCase()) ||
        (item.path &&
          item.path.toLowerCase().includes(searchValue.toLowerCase()))
    )
    setFilteredData(filterData)
  }

  // 添加/编辑
  const handleSubmit = () => {
    if (!name) {
      setAlertShow(true)
      return
    }
    if (isNew) {
      axios
        .post('/department/add', JSON.stringify({ name, number }))
        .then((res) => {
          if (res.status === 200) {
            toast((t) => <ToastCommon content={'创建成功!'} />)
            getList()
            handleModalShow()
          }
        })
        .catch(() => {
          console.error('error')
        })
    } else {
      axios
        .post('/department/update', JSON.stringify({ id, name, number }))
        .then((res) => {
          if (res.status === 200) {
            toast((t) => <ToastCommon content={'修改成功!'} />)
            getList()
            handleModalShow()
          }
        })
        .catch(() => {
          console.error('error')
        })
    }
  }

  // 编辑
  const handleEdit = (id) => {
    setIsNew(false)
    setId(id)
    setName(listData.find((item) => item._id === id).name)
    setNumber(listData.find((item) => item._id === id).number)
    handleModalShow()
  }

  // 删除
  const handleDelete = (id) => {
    setId(id)
    setConfirmModalShow(true)
  }

  const onConfirm = () => {
    axios
      .post('/department/del', JSON.stringify({ id }))
      .then((res) => {
        if (res.status === 200) {
          toast((t) => <ToastCommon content={'删除成功!'} />)
          getList()
          setConfirmModalShow(false)
        }
      })
      .catch(() => {
        console.error('error')
      })
  }

  // ** Function to handle Modal toggle
  const handleModalShow = () => setModalShow(!modalShow)

  // ** Function to handle Pagination
  const handlePagination = (page) => {
    setCurrentPage(page.selected)
  }

  // ** Custom Pagination
  const CustomPagination = () => (
    <ReactPaginate
      previousLabel=""
      nextLabel=""
      forcePage={currentPage}
      onPageChange={(page) => handlePagination(page)}
      pageCount={
        searchValue.length
          ? Math.ceil(filteredData.length / 7)
          : Math.ceil(data.length / 7) || 1
      }
      breakLabel="..."
      pageRangeDisplayed={2}
      marginPagesDisplayed={2}
      activeClassName="active"
      pageClassName="page-item"
      breakClassName="page-item"
      nextLinkClassName="page-link"
      pageLinkClassName="page-link"
      breakLinkClassName="page-link"
      previousLinkClassName="page-link"
      nextClassName="page-item next-item"
      previousClassName="page-item prev-item"
      containerClassName="pagination react-paginate separated-pagination pagination-sm justify-content-end pe-1 mt-1"
    />
  )

  return (
    <Fragment>
      <Card>
        <CardHeader className="flex-md-row flex-column align-md-items-center align-items-start border-bottom">
          <CardTitle tag="h4">部门</CardTitle>
          <div className="d-flex mt-md-0 mt-1">
            <Button
              className="ms-2"
              color="primary"
              onClick={() => {
                setIsNew(true)
                setModalShow(true)
              }}
            >
              <Plus size={15} />
              <span className="align-middle ms-50">添加</span>
            </Button>
          </div>
        </CardHeader>
        <Row className="mx-0 mb-50">
          <Col className="d-flex align-items-center  mt-1" md="10" sm="12">
            <Input
              className="dataTable-filter"
              type="text"
              id="search-input"
              placeholder="输入部门名称"
              value={searchValue}
              onChange={(e) => {
                setSearchValue(e.target.value)
              }}
              style={{ width: '40%', marginRight: '20px' }}
            />
            <Button className="ms-2" color="primary" onClick={searchData}>
              <span className="align-middle ms-50">搜索</span>
            </Button>
          </Col>
        </Row>
        <div className="react-dataTable react-dataTable-selectable-rows">
          <DataTable
            noHeader
            pagination
            columns={columns(handleEdit, handleDelete)}
            paginationPerPage={7}
            className="react-dataTable"
            sortIcon={<ChevronDown size={10} />}
            paginationComponent={CustomPagination}
            paginationDefaultPage={currentPage + 1}
            selectableRowsComponent={BootstrapCheckbox}
            data={searchValue.length ? filteredData : listData}
          />
        </div>
      </Card>

      <Modal
        isOpen={modalShow}
        toggle={handleModalShow}
        className="modal-dialog-centered"
      >
        <ModalHeader toggle={handleModalShow}>添加</ModalHeader>
        <ModalBody>
          <Row>
            <Col className="mb-1" xl="12" md="12" sm="12">
              <Label className="form-label" for="name" size="sm">
                部门名称
              </Label>
              <Input
                type="text"
                id="name"
                placeholder="请输入"
                value={name}
                bsSize="sm"
                onChange={(e) => {
                  setName(e.target.value)
                }}
              />
              <Alert color="danger" isOpen={alertShow && !name}>
                <div className="alert-body">
                  <AlertCircle size={15} />
                  <span className="ms-1">部门名称</span>
                </div>
              </Alert>
            </Col>
          </Row>
          <Row>
            <Col className="mb-1" xl="12" md="12" sm="12">
              <Label className="form-label" for="name" size="sm">
                职工人数
              </Label>
              <Input
                type="text"
                id="path"
                placeholder="请输入组件路径"
                bsSize="sm"
                value={number}
                onChange={(e) => {
                  setNumber(e.target.value)
                }}
              />
            </Col>
          </Row>
        </ModalBody>
        <ModalFooter>
          <Button color="primary" onClick={handleModalShow} outline>
            取消
          </Button>
          <Button color="primary" onClick={handleSubmit}>
            确定
          </Button>
        </ModalFooter>
      </Modal>
      <ConfirmModal
        show={confirmModalShow}
        handleConfirmModal={() => {
          setConfirmModalShow(!confirmModalShow)
        }}
        tip="确认删除吗？"
        onConfirm={onConfirm}
      />
    </Fragment>
  )
}

export default DataTableWithButtons
